<template>
  <el-dialog :class="$style.dialog" width="3.5rem" v-model="visible" destroy-on-close draggable>
    <slot name="prepend" />
    <e-form
      ref="formRef"
      :forms="forms"
      :inline="formsInline"
      :item-width="formsItemWidth"
      :label-width="formsLabelWidth"
      :i18n="i18n"
      :i18n-prefix="formsI18nPrefix"
    >
      <slot name="form" />
    </e-form>

    <slot />

    <template #footer>
      <el-button type="primary" plain notBg @click="onReset" v-if="showResetButton">{{
        resetButtonText || $t('reset')
      }}</el-button>
      <el-button type="primary" plain notBg @click="visible = false">{{
        cancelButtonText || $t('cancel')
      }}</el-button>
      <el-button type="primary" v-if="showSustainButton" :loading="loading" @click="onSustain">{{
        sustainButtonText || $t('save_and_continue_add')
      }}</el-button>
      <el-button type="primary" :loading="loading" @click="onSave">{{
        saveButtonText || $t('save')
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import eForm from '../form/index.vue'
import { useI18n } from 'vue-i18n'
import type { Props } from './type'

const props = withDefaults(defineProps<Props>(), {
  showSustainButton: false,
  forms: () => ({}),
  formsLabelWidth: '0.41rem',
  formsInline: true,
  saveAutoClose: true
})

const { t } = useI18n()
const $t = (text: string = '') => {
  return t(`component.zdialogform.${text}`)
}

const emits = defineEmits<{
  save: [model: AnyObject]
  sustain: [model: AnyObject]
}>()

const visible = defineModel<boolean>()

const formRef = ref<InstanceType<typeof eForm>>()

// 保存并继续
const onSustain = () => {
  formRef.value?.validate().then(model => {
    emits('sustain', model)
  })
}

// 保存
const onSave = () => {
  formRef.value?.validate().then(model => {
    emits('save', model)
    if (props.saveAutoClose) {
      visible.value = false
    }
  })
}

// 重置
const onReset = () => {
  formRef.value?.reset()
}
</script>

<style lang="scss" module>
@use './style.scss';
</style>
